//
//  ForgetPassWordViewController.swift
//  d11
//
//  Created by rhonin on 2018/11/14.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
class ForgetPassWordViewController: GameRootViewController {

    @IBOutlet weak var phoneText: UITextField!
    @IBOutlet weak var nameTextTel: UITextField!
    @IBOutlet weak var codeTelText: UITextField!
    @IBOutlet weak var emailText: UITextField!
    @IBOutlet weak var nameEmailText: UITextField!
    @IBOutlet weak var codeEmailText: UITextField!
    @IBOutlet weak var getCodeButTel: UIButton!
    @IBOutlet weak var getCodeTel: UILabel!
    @IBOutlet weak var butSureTel: UIButton!
    @IBOutlet weak var viewTel: UIView!
    @IBOutlet weak var viewEmail: UIView!
    @IBOutlet weak var getCodeButton: UIButton!
    @IBOutlet weak var getCode: UILabel!
    @IBOutlet weak var butsure: UIButton!
    @IBOutlet weak var telePhoneBut: UIButton!
    @IBOutlet weak var emailButton: UIButton!
    var timerE = TimerHander()
    var timerT = TimerHander()
    lazy var layerGradient =  CAGradientLayer()
    lazy var layerGradientTel =  CAGradientLayer()
    @IBOutlet weak var passEmail: UITextField!
    @IBOutlet weak var passTel: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
          self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0);
        self.title = "找回密码"
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradientTel.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradientTel.frame = CGRect(x: -2, y: -2, width: ScreenWidth+4, height: butsure.frame.height+4)
        layerGradient.frame = CGRect(x: -2, y: -2, width: ScreenWidth+4, height: butsure.frame.height+4)
        butsure.layer.addSublayer(layerGradient)
        butsure.layer.cornerRadius = 5;
        butsure.clipsToBounds = true
        butSureTel.layer.addSublayer(layerGradientTel)
        butSureTel.layer.cornerRadius = 5;
        butSureTel.clipsToBounds = true
        
        emailButton.layer.cornerRadius = 5;
        telePhoneBut.layer.cornerRadius = 5;
        
       
        getCodeButton.clipsToBounds = true
        getCodeButton.layer.cornerRadius = 6
        getCodeButton.layer.borderColor = RGBAlpa(255,198,116,1).cgColor
        getCodeButton.layer.borderWidth = 0.5
        getCodeButTel.clipsToBounds = true
        getCodeButTel.layer.cornerRadius = 6
        getCodeButTel.layer.borderColor = RGBAlpa(255,198,116,1).cgColor
        getCodeButTel.layer.borderWidth = 0.5
        self.view.bringSubviewToFront(viewEmail)
    }
    override func viewWillAppear(_ animated: Bool) {
        UIApplication.shared.setStatusBarHidden(false, with: .slide)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    @IBAction func getCode(_ sender: UIButton) {
        weak var this  = self
        if sender.tag == 0 {
            if self.nameEmailText.text?.count == 0 {
                UIHelper.alertSimpleMessage(about: "", withDescription: "请输入会员账号", in: self)
                return
            }
            if !checkEmail(email: emailText.text!) {
                UIHelper.alertSimpleMessage(about: "", withDescription: "邮箱格式错误", in: self)
                return
            }
            self.timerE.startTimer(second: 60) { (count) in
                if count > 0{
                    sender.isUserInteractionEnabled = false
                    this?.getCode.text = "\(count)"
                }else{
                    sender.isUserInteractionEnabled = true
                    this?.getCode.text = "获取验证码"
                }
            }
            self.getEmailCode()
        }else{
            if self.nameTextTel.text?.count == 0 {
                UIHelper.alertSimpleMessage(about: "", withDescription: "请输入会员账号", in: self)
                return 
            }
            if phoneText.text?.count != 11 {
                UIHelper.alertSimpleMessage(about: "", withDescription: "请输入正确手机号码", in: self)
                return
            }
            self.timerT.startTimer(second: 60) { (count) in
                if count > 0{
                    sender.isUserInteractionEnabled = false
                    this?.getCodeTel.text = "\(count)"
                }else{
                    sender.isUserInteractionEnabled = true
                    this?.getCodeTel.text = "获取验证码"
                }
            }
            self.getTelCode()
        }
    }
    
    func getEmailCode() {
        RequestHelper.post(atPath: "/clientsAPIs/getResetPassEmailToken", withData: ["name":nameEmailText.text!,"email":emailText.text!], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取邮箱验证码成功", withDescription: "请查看您的邮箱", in: self)
                    
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取邮箱验证码失败", withDescription:  json["msg"].stringValue, in: self)
                    
                }
            }
        })
    }
    
    func getTelCode() {
        RequestHelper.post(atPath: "/clientsAPIs/getResetPassMobileToken", withData: ["name":nameTextTel.text!,"mobile":phoneText.text!], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取短信验证码成功", withDescription: "请查看您的短信", in: self)
                    
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取短信验证码失败", withDescription:  json["msg"].stringValue, in: self)
                    
                }
            }
        })
    }
    
    @IBAction func buttonClick(_ sender: UIButton) {
        if sender.tag == 0{
            sender.setTitleColor(UIColor.white, for: .normal)
            sender.setImage(UIImage(named: "forget_emailWhite"), for: .normal)
            sender.setBackgroundImage(UIImage(named: "buttonBak"), for: .normal)
            telePhoneBut.setImage(UIImage(named: "regist_phone_white"), for: .normal)
             telePhoneBut.setBackgroundImage(UIImage(named: "regist_disel"), for: .normal)
            self.view.bringSubviewToFront(viewEmail)
            telePhoneBut.setTitleColor(UIColor.lightGray, for: .normal)
        }else{
             sender.setTitleColor(UIColor.white, for: .normal)
            sender.setImage(UIImage(named: "regist_phoneWhiteS"), for: .normal)
            sender.setBackgroundImage(UIImage(named: "selectTel"), for: .normal)
            emailButton.setImage(UIImage(named: "forget_email"), for: .normal)
            emailButton.setBackgroundImage(UIImage(named: "deseleEmal"), for: .normal)
            self.view.bringSubviewToFront(viewTel)
            emailButton.setTitleColor(UIColor.lightGray, for: .normal)
        }
    }
    
   

    @IBAction func surButtonCLick(_ sender: UIButton) {
        if sender.tag == 0{
            if checkEmailPass(){
                view.addSubview(self.loadingView)
                submiteEmailCode()
            }
        }else{
            if checkTelPass(){
                 view.addSubview(self.loadingView)
                submiteTelCode()
            }
        }
    }
    
    func checkEmailPass()->Bool {
        if self.nameEmailText.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入会员账号", in: self)
            return false
        }
        
        if !checkEmail(email: emailText.text!) {
            if(emailText.text?.count == 0){
                UIHelper.alertSimpleMessage(about: "", withDescription: "请输入邮箱地址", in: self)
            }else{
                UIHelper.alertSimpleMessage(about: "", withDescription: "邮箱格式错误", in: self)
            }
            return false
        }
        if self.codeEmailText.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入您的验证码", in: self)
            return false
        }
        if self.passEmail.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入您的新密码", in: self)
            return false
        }
        return true
    }
    
    func checkTelPass() -> Bool {
        if self.nameTextTel.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入会员账号", in: self)
            return false
        }
        if phoneText.text?.count != 11 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入正确手机号码", in: self)
            return false
        }
        if self.codeTelText.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入您的验证码", in: self)
            return false
        }
        if self.passTel.text?.count == 0 {
            UIHelper.alertSimpleMessage(about: "", withDescription: "请输入您的新密码", in: self)
            return false
        }
        return true
    }
    
    var sid = ""
    
    func submiteEmailCode()  {
        weak var this = self
        RequestHelper.post(atPath: "/clientsAPIs/verifyResetPassEmail", withData: ["name":nameEmailText.text!,"code":codeEmailText.text!,"email":emailText.text!], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                 DispatchQueue.main.async {
                this?.sid = json["sid"].stringValue
                this?.changePass(email: true)
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "更改密码失败", withDescription:  json["msg"].stringValue, in: self)
                    this?.loadingView.removeFromSuperview()
                }
            }
        })
    }
    
    func submiteTelCode() {
         weak var this = self
        RequestHelper.post(atPath: "/clientsAPIs/verifyresetpassmobile", withData: ["name":nameTextTel.text!,"code":codeTelText.text!,"mobile":phoneText.text!], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                    this?.sid = json["sid"].stringValue
                    this?.changePass(email: false)
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "更改密码失败", withDescription:  json["msg"].stringValue, in: self)
                     this?.loadingView.removeFromSuperview()
                }
            }
        })
    }
    
    func changePass(email:Bool) {
        var pwd = ""
        if email {
            pwd = passEmail.text!
        }else{
            pwd = passTel.text!
        }
        weak var this = self
        RequestHelper.post(atPath: "/clientsAPIs/resetpasswordalt", withData: ["pwd":pwd,"sid":sid], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                    this?.loadingView.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "更改密码成功", withDescription:  "", in: self)
                    this?.perform(#selector(this?.doLeftNaviAction), with: nil, afterDelay: 0.5)
                }
            }else{
                DispatchQueue.main.async {
                      this?.loadingView.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "更改密码失败", withDescription:  json["msg"].stringValue, in: self)
                     this?.loadingView.removeFromSuperview()
                }
            }
        })
    }
    
    // 导航栏左边按钮
    func leftButtonActionWithImg(_ image: String) {
        let naviLeftButton = UIButton.init(type: UIButton.ButtonType.custom)
        naviLeftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 22);
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.normal)
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.highlighted)
        naviLeftButton.addTarget(self, action: #selector(doLeftNaviAction), for: UIControl.Event.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: naviLeftButton)
    }
    
    @objc func doLeftNaviAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
}
